#pragma once
#include <iostream>
#include <vector>
#include <queue>
#include <pthread.h>
#include<unistd.h>
#include"Task.hpp"
using namespace std;
struct ThreadInfo
{
    pthread_t tid;
    std::string name;
};
static const int defaultnum = 5;
template <class T>
class ThreadPool
{
public:
    void Lock()
    {
        pthread_mutex_lock(&mutex_);
    }
    void UnLock()
    {
        pthread_mutex_unlock(&mutex_);
    }
    void Wait()
    {
        pthread_cond_wait(&cond_, &mutex_);
    }

private:
    static void *HandTask(void *args)
    {
        ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(args);
        std::string name = tp->GetThreadName(pthread_self());
        while (true)
        {
            // pthread_mutex_lock(&mutex_);
            tp->Lock();
            while (tp->IsQueueEmpty())
            {
                // 去等待
                // pthread_cond_wait(&cond_, &mutex_);
                tp->Wait();
            }
            T t = tp->Pop();
            // pthread_mutex_unlock(&mutex_);
            tp->UnLock();
            t();
            // cout<< name << "run,result："<< t.GetResult()<<endl;
            cout<< name << "run,result:"<< t.Result()<<endl;
            // cout << "消费了一个数据 :" << t << ", Thread name-" << name << endl;
            // sleep(1);
        }
    }

public:
    ThreadPool(int num = defaultnum) : threads_(num)
    {
        pthread_mutex_init(&mutex_, nullptr);
        pthread_cond_init(&cond_, nullptr);
    }
    ~ThreadPool()
    {
        pthread_mutex_destroy(&mutex_);
        pthread_cond_destroy(&cond_);
    }
    void Start()
    {
        int num = threads_.size();
        for (int i = 0; i < num; ++i)
        {
            threads_[i].name = "thread - " + std::to_string(i + 1);
            pthread_create(&(threads_[i].tid), nullptr, HandTask, this);
        }
    }
    T Pop()
    {
        T t = tasks_.front();
        tasks_.pop();
        return t;
    }
    void Push(const T &in)
    {
        // 往队列中push的时候，需要加锁
        // pthread_mutex_lock(&mutex_);
        Lock();
        tasks_.push(in);
        // push之后，就可以唤醒线程来进行处理
        pthread_cond_signal(&cond_);
        // pthread_mutex_unlock(&mutex_);
        UnLock();
    }
    std::string GetThreadName(pthread_t tid)
    {
        for (auto &ti : threads_)
        {
            if (ti.tid == tid)
            {
                return ti.name;
            }
        }
        return "None";
    }
    bool IsQueueEmpty()
    {
        return tasks_.empty();
    }

private:
    vector<ThreadInfo> threads_;
    std::queue<T> tasks_;

    pthread_mutex_t mutex_;
    pthread_cond_t cond_;
};